<template lang="pug">
    d2-container(:filename="filename")
        div(style="padding: 8px 0 5px 0;display:inline-block;width:100%")
            el-card(shadow="never",class="super-admin-create-user")
                div(slot="header",class="clearfix")
                    span 新建用户
                div(class="message-board")
                  el-form(:inline="true",size="small")
                    el-form-item
                        el-button(type="default",@click="addNewUser") 
                          i(class="el-icon-plus")
                          span 添加一行
                        el-button(type="primary",
                          @click="formSubmit",
                          v-if=" newUsers.length > 1  ",
                          :disabled="submiting")  
                          i(class="el-icon-check")
                          span 创建保存
                          i(class="el-icon-loading",v-if="submiting")
                    el-form-item
                        div 
                    
                el-form(label-width="70px",
                  size="mini",
                  :inline="true",
                  v-for="(newUser,index) in newUsers",
                  :model="newUser",
                  :ref="'newUser'+index"
                  style="border-bottom:1px solid #f0f0f0;margin-top:10px;")
                    el-form-item(label="用户名",
                        :rules="[{required:true,message:'设置用户名'}]",
                        prop="username")
                        el-input(placeholder="只能是英文和数字",autofocus,v-model="newUser.username",clearable)
                    el-form-item(label="密码")
                        el-input(placeholder="可留空，默认密码为:my!password@123",type="password",v-model="newUser.password",clearable)
                    el-form-item(label="角色")
                        el-select(placeholder="可留空，为普通用户，将没有任何权限",
                        v-model="newUser.roleId",
                        @change="roleChange",
                        clearable)
                            el-option(v-for="role in roles",:label="role.name",:value="role.value",:key="role.value")
                        i(class="el-icon-loading",v-if="!rolesStandBy")
                    el-form-item
                        el-button(type="danger",v-if="newUsers.length > 1",@click="removeNewUser(index)")
                          i(class="el-icon-remove-outline")
                          span 移除
                        el-button(type="primary",
                        @click="formSubmit",
                        :disabled="submiting",
                        v-if=" newUsers.length === 1  ")
                          i(class="el-icon-check")
                          span 创建保存
                          i(class="el-icon-loading",v-if="submiting")

</template>

<script>
import Vue from "vue";
import axios from "@/plugin/axios";
import util from "@/libs/util";
import NewUser from "./NewUserModel";

export default {
  name: "user-create",
  data() {
    return {
      filename: __filename,
      /**请求接口返回 */
      roles: [],
      rolesStandBy: false, // 获取角色是否完成
      /**新建用户对象 */
      newUsers: [],
      /**提交中 */
      submiting: false
    };
  },
  watch: {
    rolesStandBy(val) {
      if (val == true) this.initNewUsers();
    }
  },
  methods: {
    getRoles() {
      axios({ url: "/role/get", method: "post" }).then(roles =>
        this.setRoles(roles)
      );
    },
    setRoles(roles) {
      this.roles = roles;
      this.rolesStandBy = true;
    },
    /**
     * 获取上次选择的角色id
     * @returns {*|string}
     */
    getRoleLastSelected() {
      var roleId = util.cookies.get("user-create-role-id");
      // todo: 判断roleId是否在Roles里
      return roleId || ""; // 记录用户选择的用户ID
    },
    /**
     * 设置上次选择的角色
     * */
    setRoleLastSelected() {
      const firstNewUser = this.newUsers[0];
      if (firstNewUser && firstNewUser.roleId)
        util.cookies.set("user-create-role-id", firstNewUser.roleId);
    },
    roleChange() {
      this.setRoleLastSelected();
    },
    formSubmit() {
      var vm = this;
      var hasInValid = false;
      this.newUsers.forEach((user, index) => {
        var ref = `newUser${index}`;
        this.$refs[ref][0].validate(valid => {
          if (!valid) hasInValid = true;
        });
      });
      if (hasInValid) return; // 有不合法的数据，不提交

      this.doSubmit(); // 没不合法的，提交保存
    },
    doSubmit() {
      this.submiting = true;
      axios({
        method: "post",
        url: "superadmin/CreateUser",
        data: { model: this.newUsers }
      }).then(t => this.success(t)).catch(()=> (this.submiting=false));
    },
    success(data) {
      this.newUsers.forEach((user, index) => {
        var ref = `newUser${index}`;
        this.$refs[ref][0].resetFields();
      });
      this.$message({ type: "success", message: "创建成功" });
      this.submiting=false
    },
    resetNewUsers() {
      this.newUsers.forEach(t => {
        t.username = null;
        t.password = null;
      });
    },
    initNewUsers() {
      this.newUsers = [this.initNewUser()];
    },
    initNewUser() {
      var newUser = new NewUser();
      newUser.roleId = this.getRoleLastSelected();
      return newUser;
    },
    addNewUser() {
      this.newUsers.push(this.initNewUser());
    },
    removeNewUser(index) {
      this.newUsers.splice(index, 1);
    }
  },
  created() {
    this.getRoles();
  }
};
</script>

<style lang="scss">
.super-admin-create-user {
  min-width: 1100px;

  .message-board {
    $height: 60px;
    height: $height;
    line-height: $height;
  }
}
</style>
